// pages/awardDetails/awardDetails.js

const service = require('./awardDetailsServer.js')
const utilService = require('../../utils/utilService.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    details:null,
    shareMsg:"",
    currentItem:"1",
    hasNextPage: false,
    startPage:0,
    isLoadMore: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getShareMessage(5)
    this.requestData(this.data.currentItem - 1,false)
  },
  /**
   * 切换 item
   */
  switchItemRequest:function(item){
    this.setData({
      currentItem: item,
      hasNextPage: false,
      startPage: 0,
      details:null,
    })
    this.requestData(this.data.currentItem-1,false);
  },
  requestData: function (flag,addMore){
    var self = this;
    if(addMore){
      this.setData({
        isLoadMore: true,
      })
    }else{
      wx.showLoading({
        title: '正在努力加载',
      })
    }
    service.requestDetail(flag,this.data.startPage,(res) => {
      wx.hideLoading()
      var source = new Array;
      if (addMore){
        var datas = res.items;
        for (var i = 0; i < datas.length; i++) {
          datas[i].count > 0 ? datas[i].count = "+" + datas[i].count : datas[i].count;
        }
        source = self.data.details.concat(datas)
        self.setData({
          isLoadMore: false,
          details: source,
          hasNextPage: res.hasNextPage,
          startPage: res.nextPage
        })
      }else{
        source = res.items
        for (var i = 0; i < source.length; i++) {
          source[i].count > 0 ? source[i].count = "+" + source[i].count : source[i].count;
        }
        self.setData({
          details: source,
          hasNextPage: res.hasNextPage,
          startPage: res.nextPage
        })
      }
    },(err) =>{
      wx.hideLoading()
      self.setData({
        isLoadMore: false,
      })
    });
  },

  /**
   * view触底监听
   */
  onReachBottom: function () {
    
    // 当前页是最后一页
    if (!this.data.hasNextPage) {
      this.setData({
        loadMoreData: '暂无更多数据'
      })
      return;
    }
    this.requestData(this.data.currentItem - 1,true)
  },

  //获取分享信息
  getShareMessage: function (type) {
    var self = this;
    utilService.shareSettings(type,
      function (data) {
        console.log("分享数据", data)
        self.setData({
          shareMsg: data.title
        })
      },
      function (error) {

      }
    );
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var title = this.data.shareMsg
    var path = "pages/home/home?userId=" + getApp().globalData.userId
    return {
      title: title,
      path: path,
      success: function (res) {
      },
      fail: function (res) {
      }
    }
  },
  switchItem:function(event){
    var index = event.currentTarget.dataset.id;
    this.switchItemRequest(index);
    console.log(index);
    
  }
})